package com.qi.demo01.future;

/**
 * @author zjq
 * @date 2020/3/30 13:15
 */

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步调用  （类似于AJAX）CompletableFuture
 * 异步执行
 * 成功回调
 * 失败回调
 */
public class futureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        // 发起一个请求
        //没有返回值的runSync异步回调
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"runAsync=》Void");
//        });
//
//        System.out.println("先执行这个");
//
//        completableFuture.get();

        //有返回值的异步回调
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "supplyAsync=>String");
            return 123 + "";
        });

        System.out.println("先执行这个");

        completableFuture.whenComplete((t, u) -> {
            System.out.println("t===" + t);//正常的返回结果
            System.out.println("u===" + u);//错误的信息
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233 + "";//可以获取到错误的返回结果
        }).get();

    }
}
